package com.club.common.security;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.club.common.constant.JwtConstant;
import com.club.entity.CheckResult;
import com.club.entity.SysOperation;
import com.club.entity.SysUser;
import com.club.mapper.SysOperationMapper;
import com.club.service.SysUserService;
import com.club.util.*;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * @author chaochao(vx : zhangfec)
 */
@Slf4j
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private MyUserDetailServiceImpl myUserDetailService;

    @Autowired
    private SysUserService sysUserService;

    @Resource
    private SysOperationMapper sysOperationMapper;

    // 请求白名单
    private static final String URL_WHITELIST[] = {
            "",
            "/index.html",
            "/",
            "/favicon.ico",
            "/captcha",
            "/user/register"
    };

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        String requestURI = request.getRequestURI();
        System.out.println("request.getRequestURI()" + requestURI);
        if (StringUtil.isEmpty(token) || new ArrayList<String>(Arrays.asList(URL_WHITELIST)).contains(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
        CheckResult checkResult = JwtUtils.validateJWT(token);
        if (!checkResult.isSuccess()) {
            switch (checkResult.getErrCode()) {
                case JwtConstant.JWT_ERRCODE_NULL:
                    throw new JwtException("Token不存在");
                case JwtConstant.JWT_ERRCODE_FAIL:
                    throw new JwtException("Token验证不通过");
                case JwtConstant.JWT_ERRCODE_EXPIRE:
                    throw new JwtException("Token过期");
            }
        }


        Claims claims = JwtUtils.parseJWT(token);
        String username = claims.getSubject();

        SysUser sysUser = sysUserService.getByUserName(username);
        //记录操作
        Map<String, String> uriMap = RequestURIUtil.uriConvertOperation();
        for (Map.Entry<String, String> stringObjectEntry : uriMap.entrySet()) {
            String key = stringObjectEntry.getKey();
            if (StrUtil.contains(requestURI, key)) {
                String value = stringObjectEntry.getValue();
                SysOperation sysOperation = SysOperation.builder()
                        .userId(Convert.toInt(sysUser.getId()))
                        .operateMsg(value)
                        .loginTime(sysUser.getLoginDate())
                        .createTime(new Date())
                        .build();
                sysOperationMapper.insert(sysOperation);
            }
        }

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, myUserDetailService.getUserAuthority(sysUser.getId()));

        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        chain.doFilter(request, response);

    }
}
